package org.example.easyexceltest.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.example.easyexceltest.entity.Other;
import org.example.easyexceltest.entity.User;
import org.example.easyexceltest.mapper.UserMapper;
import org.example.easyexceltest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ningshangxu
 * @since 2024-08-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser(List<User> users) {
        userMapper.saveUser(users);
    }

    @SneakyThrows
    @Override
    public void limitSelect(HttpServletResponse response)  {
        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();


        WriteSheet writeSheet1 = EasyExcel.writerSheet("user").head(User.class).build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet("other").head(Other.class).build();

        Long pageSize = 5000L;
        Long pageNo = 0L;
        Long l = userMapper.selectCount(null);
        Long times = l / pageSize;
        Long rest = l % pageSize;
        for (int i = 0; i < times ; i++) {
            List<User> users = userMapper.limitSelect(pageNo, pageSize);
            writer.write(users, writeSheet1);
            pageNo += pageSize;
        }
        if (rest > 0) {
            List<User> users = userMapper.limitSelect(pageNo, rest);
            writer.write(users, writeSheet1);
        }

        writer.finish();
    }
}
